package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.pojo.MsslyyComment;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.MsslyyCommentMapper;
import com.example.pojo.MsslyyUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@Service
public class MsslyyCommentService extends ServiceImpl<MsslyyCommentMapper, MsslyyComment> {

    @Resource
    private MsslyyCommentMapper msslyyCommentMapper;
    @Resource
    private MsslyyUserService msslyyUserService;

    /**
     * 根据id查到到书籍的评论并处理返回
     * @param bookId 书籍id
     * @return 处理好的评论
     */
    public List<MsslyyComment> getCommentByBookId(Long bookId){
        LambdaQueryWrapper<MsslyyComment> queryWrapper = Wrappers
                .<MsslyyComment>lambdaQuery()
                .eq(MsslyyComment::getBookId, bookId)
                .orderByDesc(MsslyyComment::getId);
        //根据书籍查找所有评论
        List<MsslyyComment> list = list(queryWrapper);
        list.forEach(e->e.setChildren(new ArrayList<>()));
        list.forEach(e->{
            //找出评论人
            MsslyyUser one = msslyyUserService.getOne(Wrappers.<MsslyyUser>lambdaQuery().eq(MsslyyUser::getId, e.getUserId()));
            e.setUserImages(one.getUserImages());
            e.setUserNickName(one.getUserNickName());
            //如果存在父评论
            if (e.getParentId()!=0){
                list.forEach(c->{
                    if (c.getId().equals(e.getParentId())){
                        List<MsslyyComment> children = c.getChildren();
                        children.add(e);
                        c.setChildren(children);
                    }
                });
            }
        });
        return list;
    }

}
